<?php

namespace Module\Cms;

use Manager\User as Manager;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 注册组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Register extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
        /** 如果已经登录 */
        if ($this->auth->hasLogin() || !$this->config->allowRegister) {
			
			$this->redirect($this->config->siteUrl);
			
        }
		
		# 定义变量默认数据
		$this->parameter([

			# 设置主体
			'main' => 'register',
			
			# 主题目录
			'themeDir' => file_exists($this->themeFile('register.php')) 
			    ? $this->themeFile()
				: W3_ROOT_DIR . 'system/static/html/',
			
			# 主题文件
			'themeFile' => 'register',
			
			# 默认keywords
			'title' => __('注册'),
			
	    ], true);
	}
	
    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
		/** 输出内容 */
		$this->request->isGet() 
		    && $this->layout->set($this->registerForm());

		$this->on($this->request->isPost())->action();
	}

    /**
     * 初始化函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$form = $this->registerForm();

		/** 验证表单 */
        if ($form->validate()) {
            $this->goBack();
        }

        $user = $this->request->from(array_keys($form->getInputs()));
        $user['nickName'] = empty($user['nickName']) ? $user['name'] : $user['nickName'];
        $user['created'] = $this->config->time;		
		$user['group'] = 'member';

        $insertId = $this->addUser($user);
        $this->db
		   ->select()
		   ->from('table.users')
		   ->where('uid = ?', $insertId)
           ->limit(1)
		   ->fetch([$this, 'push']);

        $this->auth->login($this->request->name, $this->request->password);
		
        /** 设置提示信息 */
        $this->notice(
		    __('用户 <strong>%s</strong> 已经成功注册, 密码为 <strong>%s</strong>', [$this->nickName, $this->request->password]),
			'success'
		);
		
		$this->redirect($this->adminUrl(false));
    }
}
